package edu.washington.cs.workflow.analysis.guistructure;

import java.util.LinkedList;
import java.util.List;

import edu.washington.cs.workflow.util.Files;
import edu.washington.cs.workflow.util.Utils;

/**
 * Given a trace file. this class recovers a list of method entities
 * from it.
 * */
public class EventTraceRecoverer {

	public final String[] traceFiles;
	
	public EventTraceRecoverer(String traceFile) {
		this(new String[]{traceFile});
//		Utils.checkNotNull(traceFile);
//		Files.checkFileExistence(traceFile);
//		this.traceFile = traceFile;
	}
	
	public EventTraceRecoverer(String[] traceFiles) {
		Utils.checkNotNull(traceFiles);
		for(String traceFile : traceFiles) {
			Files.checkFileExistence(traceFile);
		}
		this.traceFiles = traceFiles;
	}
	
	private List<String> readAllFiles(String[] traceFiles) {
		List<String> lines = new LinkedList<String>();
		for(String traceFile : traceFiles) {
			List<String> content = Files.readWholeNoExp(traceFile);
			lines.addAll(content);
		}
		return lines;
	}
	
	private boolean ignoreError = true;
	
	public List<EventEntity> recoverEventEntities() {
		int skip = 0, action = 0, entity = 0, handler = 0;
		List<EventEntity> entities = new LinkedList<EventEntity>();
		List<String> lines = readAllFiles(this.traceFiles);//Files.readWholeNoExp(traceFile);
		int num = 0;
		for(String line : lines) {
			num++;
			if(line.trim().isEmpty()) {
				skip++;
				continue;
			}
			EventEntity e = null;
			if(line.startsWith(UIActionEntity.TYPE)) {
				action++;
				e = UIActionEntity.recover(line);
			} else if (line.startsWith(UIMethodEntity.TYPE)) {
				entity++;
				e = UIMethodEntity.recover(line);
			} else if (line.startsWith(UIActionHandler.TYPE)) {
				handler++;
				e = UIActionHandler.recover(line);
			} else {
				if(!ignoreError) {
				    throw new Error("unexpected line: " + line + ", line num: " + num);
				} else {
				    Utils.debugPrintln("unexpected line: " + line + ", line num: " + num);
				    continue;
				}
			}
			Utils.checkNotNull(e);
			entities.add(e);
		}
		if(!ignoreError) {
		    Utils.checkTrue(lines.size() == (skip + action + entity + handler));
		}
		System.out.println("skip: " + skip + ", action: " + action + ", entity: " + entity + ", handler: " + handler);
		return entities;
	}
}
